package com.Mybatis3源码深度解析.c2;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;

import org.apache.ibatis.io.Resources;
import org.junit.Test;

/**
 * 获取数据库自增主键
 */
public class GetGeneratedKeysDemo {

    @Test
    public void testJdbc() {
        try {
        	// 初始化数据
            Class.forName("com.mysql.jdbc.Driver");
            Properties prop = Resources.getResourceAsProperties("hikariPool.properties");
            // 获取Connection对象
            Connection conn = DriverManager.getConnection(prop.getProperty("jdbcUrl"), prop.getProperty("dataSource.user"), prop.getProperty("dataSource.password"));
            Statement stmt = conn.createStatement();
            String sql = "insert into test(title) " +
                    "values('Mybatis3源码深度解析');";
            stmt.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
            ResultSet genKeys = stmt.getGeneratedKeys();
            if(genKeys.next()) {
                System.out.println("自增长主键：" + genKeys.getInt(1));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
